package com.yanmushi.ms.api.dlc.context;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @auther yinlei
 * @date 2018/1/23
 * @since 1.0.0
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

                String auth = request.getHeader("authorization");
                String token = request.getParameter("token");
                if (token == null) {
                    if (auth == null) {
                        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                        return false;
                    } else {
                        token = auth;
                    }
                }

                HttpClient client = HttpClientBuilder.create().build();
                HttpGet post = new HttpGet("http://test-id:test-secret@localhost:8080/oauth/check_token?token=" + token);

                HttpResponse resp = client.execute(post);
                if (resp.getStatusLine().getStatusCode() == 200) {
                    return true;
                }

                response.setStatus(HttpServletResponse.SC_FORBIDDEN);

                return false;
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

            }
        });


        super.addInterceptors(registry);
    }
}
